package com.ls.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ls.config.satoken.SaTokenUtilPy;
import com.ls.controller.holiday.model.*;
import com.ls.entity.*;
import com.ls.mapper.HolidayMapper;
import com.ls.service.*;
import com.ls.utils.ResultData;
import com.nlf.calendar.Lunar;
import com.nlf.calendar.Solar;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

import static com.ls.constant.SystemConstants.*;
import static com.ls.constant.SystemConstants.VALID_TRUE;
import com.ls.utils.pay.TimeUtils;
/**
 * <p>
 * 节假日 服务实现类
 * </p>
 *
 * @author pengyu
 * @since 2024-10-12
 */
@Service
@Slf4j
public class HolidayServiceImpl extends ServiceImpl<HolidayMapper, Holiday> implements IHolidayService {
    @Lazy
    private final ICustomerService customerService;
    @Lazy
    private final ISmsRuleService smsRuleService;
    @Lazy
    private final IRuleLinkmanService ruleLinkmanService;
    @Lazy
    private final ILinkmanService linkmanService;
    @Lazy
    private final ISmsTemplateService smsTemplateService;
    @Lazy
    private final IRuleTemplateService ruleTemplateService;

    @Autowired
    public HolidayServiceImpl(@Lazy ICustomerService customerService,
                              @Lazy ISmsRuleService smsRuleService,
                              @Lazy IRuleLinkmanService ruleLinkmanService,
                              @Lazy ILinkmanService linkmanService,
                              @Lazy ISmsTemplateService smsTemplateService,
                              @Lazy IRuleTemplateService ruleTemplateService
    ) {
        this.customerService = customerService;
        this.smsRuleService = smsRuleService;
        this.ruleLinkmanService = ruleLinkmanService;
        this.linkmanService = linkmanService;
        this.smsTemplateService = smsTemplateService;
        this.ruleTemplateService = ruleTemplateService;
    }

    /**
     * 新增节假日
     */
    @Override
    public ResultData add(AddHolidayModel model) {
        log.info("新增节假日：{}", model);
        //判断当前用户是否存在重复的分类
        Holiday holiday1 = getOne(new LambdaQueryWrapper<Holiday>()
                .eq(Holiday::getCustomerId, model.getCustomerId())
                .eq(Holiday::getValidFlag, VALID_TRUE)
                .eq(Holiday::getCategoryId, model.getCategoryId())
                .eq(Holiday::getHolidayName, model.getHolidayName()));
        if (holiday1 != null) {
            return ResultData.failure("当前用户已存在该节日！");
        }
        Holiday holiday = new Holiday();
        BeanUtils.copyProperties(model, holiday);
        holiday.setCreateTime(LocalDateTime.now());
        holiday.setUpdateTime(LocalDateTime.now());
        holiday.setValidFlag(VALID_TRUE);
        Boolean flag = saveOrUpdate(holiday);
        if (flag) {
            return ResultData.successMsg("新增成功");
        } else {
            return ResultData.failure("新增失败");
        }
    }

    /**
     * 查询节日是否能直接删除或者编辑 type为0删除，1为编辑
     */
    @Override
    public ResultData getHolidayStatus(Long holidayId, Integer type) {
        HolidayStatusVo holidayStatusVo = new HolidayStatusVo();
        List<SmsRule> smsRuleList = smsRuleService.list(new LambdaQueryWrapper<SmsRule>()
                        .eq(SmsRule::getHolidayId, holidayId)
//                .eq(SmsRule::getValidFlag, VALID_TRUE)
        );
        if (smsRuleList.size() > 0) {
            holidayStatusVo.setStatus(false);
            if (type == NUMBER_0) {
                holidayStatusVo.setMessage("已添加关怀事件，不可删除");
            } else {
                holidayStatusVo.setMessage("已添加关怀事件，不可编辑");
            }
        } else {
//            List<SmsRule> smsRuleList2 = smsRuleService.list(new LambdaQueryWrapper<SmsRule>()
//                    .eq(SmsRule::getHolidayId, holidayId)
//                    .eq(SmsRule::getValidFlag, VALID_FALSE)
//            );
//            if (smsRuleList2.size() > 0 && type == NUMBER_0) {
//                holidayStatusVo.setMessage("请确认是否删除，删除对应节日后，节日绑定的模板，规则也会同步删除！");
//            }
            holidayStatusVo.setStatus(true);
        }
        return ResultData.successData(holidayStatusVo);
    }

    /**
     * 更新节假日
     */
    @Override
    public ResultData edit(EditHolidayModel model) {
        log.info("更新节假日：{}", model);
        ResultData resultData1 = getHolidayStatus(model.getHolidayId(), NUMBER_1);
        HolidayStatusVo holidayStatusVo = (HolidayStatusVo) resultData1.getData();
        //判断当前用户是否存在重复的分类
        Holiday holiday1 = getOne(new LambdaQueryWrapper<Holiday>()
                .eq(Holiday::getCustomerId, model.getCustomerId())
                .eq(Holiday::getCategoryId, model.getCategoryId())
                .eq(Holiday::getValidFlag, VALID_TRUE)
                .eq(Holiday::getHolidayName, model.getHolidayName())
                .ne(Holiday::getHolidayId, model.getHolidayId()));
        if (holiday1 != null) {
            return ResultData.failure("当前用户已存在该分类！");
        }
        Holiday holiday = getById(model.getHolidayId());
        if (!holidayStatusVo.getStatus() && holiday.getCustomerId() != 0) {
            return ResultData.failure(holidayStatusVo.getMessage());
        }
        BeanUtils.copyProperties(model, holiday);
        holiday.setUpdateTime(LocalDateTime.now());
        Boolean flag = saveOrUpdate(holiday);
        if (flag) {
            return ResultData.successMsg("更新成功");
        } else {
            return ResultData.failure("更新失败");
        }
    }

    /**
     * 删除节假日
     */
    @Override
    public ResultData del(Long holidayId) {
        ResultData resultData1 = getHolidayStatus(holidayId, NUMBER_0);
        HolidayStatusVo holidayStatusVo = (HolidayStatusVo) resultData1.getData();
        if (!holidayStatusVo.getStatus()) {
            return ResultData.failure(holidayStatusVo.getMessage());
        }
        Customer customer = SaTokenUtilPy.getCustomer();
        Long customerId = customer.getCustomerId();
        List<Long> ruleIds = smsRuleService.list(new LambdaQueryWrapper<SmsRule>()
                                .eq(SmsRule::getHolidayId, holidayId)
                                .eq(SmsRule::getCustomerId, customerId)
//                        .eq(SmsRule::getValidFlag, VALID_FALSE)
                ).stream()
                .map(SmsRule::getRuleId)
                .collect(Collectors.toList());
        log.info("删除节日下的所有事件：{}", ruleIds);
        log.info("删除节日下的所有事件长度：{}", ruleIds.size());
        if (ruleIds != null && ruleIds.size() > 0) {
            return ResultData.failure("请先删除节日下的所有事件");
        }
        List<Long> holidayIds = smsTemplateService.list(new LambdaQueryWrapper<SmsTemplate>()
                        .eq(SmsTemplate::getHolidayId, holidayId)
                        .eq(SmsTemplate::getCustomerId, customerId)
                ).stream()
                .map(SmsTemplate::getHolidayId)
                .collect(Collectors.toList());
        if (holidayIds != null && holidayIds.size() > 0) {
            return ResultData.failure("请先删除节日下的所有模板");
        }
//        smsRuleService.remove(new LambdaQueryWrapper<SmsRule>().in(SmsRule::getRuleId, ruleIds));
//        ruleTemplateService.remove(new LambdaQueryWrapper<RuleTemplate>().eq(RuleTemplate::getRuleId, ruleIds));
//        ruleLinkmanService.remove(new LambdaQueryWrapper<RuleLinkman>().in(RuleLinkman::getRuleId, ruleIds));
//        smsTemplateService.remove(new LambdaQueryWrapper<SmsTemplate>().eq(SmsTemplate::getHolidayId, holidayId));
        Holiday holiday = getById(holidayId);
        holiday.setUpdateTime(LocalDateTime.now());
        holiday.setValidFlag(VALID_FALSE);
        Boolean flag = saveOrUpdate(holiday);
        if (flag) {
            return ResultData.successMsg("删除成功");
        } else {
            return ResultData.failure("删除失败");
        }
    }

    /**
     * 查询节假日
     */
    @Override
    public ResultData getHoliday(Long categoryId, Long customerId, Integer showBirth, Integer showExist, Integer categoryType) {
        List<Holiday> holidayList = list(new LambdaQueryWrapper<Holiday>()
                .eq(categoryId != null, Holiday::getCategoryId, categoryId)
                .eq(customerId != null, Holiday::getCustomerId, customerId)
                .eq(showExist != null, Holiday::getValidFlag, VALID_TRUE)
                .in(categoryType != null, Holiday::getCategoryId, Arrays.asList(1, 2, 3, 4))
                .ne(showBirth == null, Holiday::getHolidayName, HOLIDAY_CONTENT_TYPE_BIRTHDAY)
                .orderByDesc(Holiday::getCreateTime)
        );
        if (!holidayList.isEmpty()) {
            holidayList.forEach(holiday -> {
                if (holiday.getCustomerId() != 0) {
                    //根据用户id查询用户
                    log.info("查询用户：{}", holiday.getCustomerId());
                    String phone = customerService.getById(holiday.getCustomerId()).getPhone();
                    holiday.setCustomerPhone(phone);
                }
            });
        }
        return ResultData.successData(holidayList);
    }

    /**
     * app查询节假日
     */
    @Override
    public ResultData getAppHoliday(Long categoryId) {
        Customer customer = SaTokenUtilPy.getCustomer();
        Long customerId = customer.getCustomerId();
        List<Holiday> holidayList = list(new LambdaQueryWrapper<Holiday>()
                .eq(categoryId != null, Holiday::getCategoryId, categoryId)
                .and(q -> q.eq(Holiday::getCustomerId, customerId)
                        .or()
                        .eq(Holiday::getCustomerId, 0))
                .eq(Holiday::getValidFlag, VALID_TRUE)
                .ne(Holiday::getHolidayName, HOLIDAY_CONTENT_TYPE_BIRTHDAY)
        );

        // 1. 按月份分组并排序
        Map<Integer, List<Holiday>> groupedByMonth = holidayList.stream()
                .sorted(Comparator.comparing((Holiday h) -> h.getStartTime().getMonthValue())
                        .thenComparing(h -> h.getStartTime().getDayOfMonth()))
                .collect(Collectors.groupingBy(
                        h -> h.getStartTime().getMonthValue(),
                        LinkedHashMap::new,
                        Collectors.toList()));

        // 2. 转换为目标数据结构
//        List<Map<String, Object>> result = groupedByMonth.entrySet().stream()
//                .sorted(Map.Entry.comparingByKey())
//                .map(entry -> {
//                    Map<String, Object> monthData = new LinkedHashMap<>();
//                    monthData.put("month", entry.getKey());
//                    monthData.put("data", entry.getValue());
//                    return monthData;
//                }).collect(Collectors.toList());
// 2. 转换为目标数据结构（增加日期格式转换）
        List<Map<String, Object>> result = groupedByMonth.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .map(entry -> {
                    Map<String, Object> monthData = new LinkedHashMap<>();
                    monthData.put("month", entry.getKey());

                    List<Map<String, Object>> processedData = entry.getValue().stream()
                            .map(holiday -> {
                                Map<String, Object> item = new LinkedHashMap<>();
                                // 手动拷贝所有属性到item
                                item.put("holidayId", holiday.getHolidayId());
                                item.put("holidayName", holiday.getHolidayName());
                                item.put("customerId", holiday.getCustomerId());
                                item.put("categoryId", holiday.getCategoryId());
                                item.put("holidayType", holiday.getHolidayType());
                                item.put("holidaySort", holiday.getHolidaySort());
                                item.put("period", holiday.getPeriod());
                                item.put("periodCount", holiday.getPeriodCount());
                                item.put("createTime", holiday.getCreateTime().format(DateTimeFormatter.ISO_DATE));
                                item.put("updateTime", holiday.getUpdateTime().format(DateTimeFormatter.ISO_DATE));
                                item.put("validFlag", holiday.getValidFlag());

                                // 日期格式转换
                                if (holiday.getHolidayType() == 0) {
                                    item.put("startTime", TimeUtils.convertToLunar(holiday.getStartTime(), 1));
                                } else {
                                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M月d日");
                                    item.put("startTime", holiday.getStartTime().format(formatter));
                                }
                                return item;
                            }).collect(Collectors.toList());

                    monthData.put("data", processedData);
                    return monthData;
                }).collect(Collectors.toList());
        return ResultData.successData(result);
    }

    /**
     * 查询节日动态
     */
    @Override
    public ResultData getHolidayDynamic(QueryHolidayModel model) {
        Customer customer = SaTokenUtilPy.getCustomer();
        Long customerId = customer.getCustomerId();
        log.info("customerId：{}", customerId);
        LambdaQueryWrapper<Holiday> wrapper = new LambdaQueryWrapper<>();
        log.info("model：{}", model);
        if (model.getCategoryId() == null) {
            log.info("查询所有节假日");
            wrapper.eq(Holiday::getCustomerId, customerId)
                    .or()
                    .eq(Holiday::getCustomerId, NUMBER_0);
        } else if (model.getCategoryId() == 2) {
            wrapper.eq(Holiday::getHolidayId, 6);
        } else if (model.getCategoryId() == 1) {
            wrapper.in(Holiday::getCategoryId, Arrays.asList(1, 2, 3, 4));
        } else {
            wrapper.eq(Holiday::getCustomerId, customerId)
                    .eq(Holiday::getCategoryId, model.getCategoryId());
        }
        List<Holiday> holidayList = list(wrapper);
        log.info("holidayList：{}", holidayList.size());
        //近一个月的节日
        List<HolidayCountModel> holidayMonthList = new ArrayList<>();
        //一个月之后
        List<HolidayCountModel> holidayNoMonthList = new ArrayList<>();
        if (model.getCategoryId() == null || model.getCategoryId() != 2) {
            holidayList.forEach(holiday -> {
                HolidayCountModel holidayCountModel = new HolidayCountModel();
                if (holiday.getHolidayId() == 6) {
                    return;
                }
                log.info("holiday：{}", holiday);
                //节日下次执行时间
                LocalDate date = TimeUtils.getNextExecuteDate(0,holiday, LocalDate.now());
                log.info("查询时间：{}", date);
                //查询一年内的节日
                log.info("查询符合条件时间：{}", date);
                holidayCountModel.setHolidayId(holiday.getHolidayId());
                holidayCountModel.setHolidayName(holiday.getHolidayName());
                List<Long> ruleIds = smsRuleService.list(new LambdaQueryWrapper<SmsRule>()
                        .eq(SmsRule::getHolidayId, holiday.getHolidayId())
                        .eq(SmsRule::getCustomerId, customerId)
                        .eq(SmsRule::getValidFlag, VALID_TRUE)
                ).stream().map(SmsRule::getRuleId).collect(Collectors.toList());
                log.info("ruleIds：{}", ruleIds);
                int[] numArray = {0};
                if (ruleIds.size() > 0) {
                    ruleIds.forEach(ruleId -> {
                        List<RuleLinkman> ruleLinkmanList = ruleLinkmanService.list(new LambdaQueryWrapper<RuleLinkman>()
                                .eq(RuleLinkman::getRuleId, ruleId)
                        );
                        numArray[0] += ruleLinkmanList.size();
                    });
                }
                holidayCountModel.setRemindNum(numArray[0]);
                holidayCountModel.setDateType(holiday.getHolidayType());
                String remindDate;
                if (holiday.getHolidayType() == 1) {
                    remindDate =date.toString();
                } else {
                    remindDate = date + "（" + TimeUtils.convertToLunar2(date, 1) + "）";
                }
                holidayCountModel.setRemindDate(remindDate);
                holidayCountModel.setCountDown((int) ChronoUnit.DAYS.between(LocalDate.now(), date));
                LocalDate startDate = LocalDate.now();
                LocalDate endDate = LocalDate.now().plusMonths(1);
                log.info("查询节日动态startDate：{}", startDate);
                log.info("查询节日动态endDate：{}", endDate);
//
                //判断时间是否在这个月月底之前
                if ((date.isEqual(startDate) || date.isAfter(startDate))
                        && date.isBefore(endDate)) {
                    log.info("本月：{}", holidayCountModel);
                    if (holiday.getPeriod()!=0||holiday.getPeriod()==0&&date.isAfter(LocalDate.now())){
                        holidayMonthList.add(holidayCountModel);
                        log.info("本月：{}", holidayMonthList);
                    }
                } else {
                    if (holiday.getPeriod()!=0||holiday.getPeriod()==0&&date.isAfter(LocalDate.now())){
                        log.info("非本月：{}", holidayCountModel);
                        holidayNoMonthList.add(holidayCountModel);
                        log.info("非本月：{}", holidayNoMonthList);
                    }
                }
            });
        }
        if (model.getCategoryId() == null || model.getCategoryId() == 2) {
            List<Linkman> linkmanList = linkmanService.list(new LambdaQueryWrapper<Linkman>()
                    .eq(Linkman::getCustomerId, customerId)
                    .isNotNull(Linkman::getLinkmanBirthday)
                    .eq(Linkman::getValidFlag, VALID_TRUE)
            );
            log.info("查询过生日的联系人：{}", linkmanList);
            linkmanList.forEach(linkman -> {
                HolidayCountModel holidayCountModel = new HolidayCountModel();
                log.info("查询时间：{}", linkman.getLinkmanBirthday());
                //模拟获取下一次执行时间
                Holiday holiday1 = new Holiday();
                holiday1.setStartTime(linkman.getLinkmanBirthday());
                holiday1.setHolidayType(linkman.getBirthdayType());
                holiday1.setPeriod(1);
                holiday1.setPeriodCount(1);
                holiday1.setHolidaySort(0);
                LocalDate date = TimeUtils.getNextExecuteDate(0,holiday1, LocalDate.now());
                log.info("查询阳历时间：{}", date);
                holidayCountModel.setHolidayId(6L);
                String name="";
                if (StringUtils.isNotEmpty(linkman.getLinkmanName())){
                    name=linkman.getLinkmanName();
                }else {
                    name="匿名";
                }
                holidayCountModel.setHolidayName(name+"的生日");
                holidayCountModel.setRemindNum(1);
                holidayCountModel.setDateType(linkman.getBirthdayType());
                String remindDate;
                if (linkman.getBirthdayType() == 1) {
                    remindDate = date.toString();
                } else {
                    remindDate = date + "（" + TimeUtils.convertToLunar2(date, 1) + "）";
                }
                holidayCountModel.setRemindDate(remindDate);
                holidayCountModel.setCountDown((int) ChronoUnit.DAYS.between(LocalDate.now(), date));
                LocalDate startDate = LocalDate.now();
                LocalDate endDate = LocalDate.now().plusMonths(1);
                //判断时间是否在这个月月底之前
                if ((date.isEqual(startDate) || date.isAfter(startDate))
                        && date.isBefore(endDate)) {
                    holidayMonthList.add(holidayCountModel);
                } else {
                    holidayNoMonthList.add(holidayCountModel);
                }
            });
        }
        log.info("holidayMonthList：{}", holidayMonthList);
        log.info("holidayNoMonthList：{}", holidayNoMonthList);
        // 在分页参数处理前添加排序逻辑
        holidayMonthList.sort(Comparator.comparingInt(HolidayCountModel::getCountDown));
        holidayNoMonthList.sort(Comparator.comparingInt(HolidayCountModel::getCountDown));
        Map<String, Object> result = new HashMap<>();
        result.put("currentMonth", holidayMonthList);
        // 分页参数处理
        int pageSize = model.getPageSize() != null ? model.getPageSize() : 10;
        int pageNum = model.getPageNum() != null ? model.getPageNum() : 1;
        int total = holidayNoMonthList.size();

        // 计算分页
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);
        List<HolidayCountModel> pagedList = holidayNoMonthList.subList(Math.max(fromIndex, 0), Math.min(toIndex, total));

        // 构建分页结果
        Map<String, Object> pageInfo = new HashMap<>();
        pageInfo.put("pageNum", pageNum);
        pageInfo.put("pageSize", pageSize);
        pageInfo.put("total", total);
        pageInfo.put("pages", (int) Math.ceil((double) total / pageSize));

        result.put("nextMonth", pagedList);
        result.put("pageInfo", pageInfo);

        return ResultData.successData(result);
    }

    /**
     * 查询设置了生日的联系人数组
     */
    public List<Long> getSetBirthdayLinkmanIdList() {
        Customer customer = SaTokenUtilPy.getCustomer();
        Long customerId = customer.getCustomerId();
        List<Long> linkmanIdList = new ArrayList<>();

        //根据条件查询生日启用规则的id
        List<SmsRule> ruleList = smsRuleService.list(new LambdaQueryWrapper<SmsRule>()
                .eq(SmsRule::getCustomerId, customerId)
                .eq(SmsRule::getValidFlag, VALID_TRUE)
                .eq(SmsRule::getTemplateCategory, TEMPLATE_CATEGORY_CARE)
                .eq(SmsRule::getHolidayId, 6)
        );
        log.info("设置了生日规则:{}", ruleList);
        if (ruleList.size()>0) {
            for (SmsRule smsRule : ruleList){
                List<RuleLinkman> ruleLinkmanList = ruleLinkmanService.list(new LambdaQueryWrapper<RuleLinkman>()
                        .eq(RuleLinkman::getCustomerId, customerId)
                        .eq(RuleLinkman::getRuleId, smsRule.getRuleId())
                );
                for (RuleLinkman ruleLinkman : ruleLinkmanList){
                    linkmanIdList.add(ruleLinkman.getLinkmanId());
                }
            }
        }
        log.info("已设置生日的id:{}", linkmanIdList);
        return linkmanIdList;
    }

    /**
     * 查询未设置生日的数量
     */
    @Override
    public ResultData getNotSetBirthdayCount() {
        Customer customer = SaTokenUtilPy.getCustomer();
        Long customerId = customer.getCustomerId();
        List<Long> linkmanIdList = getSetBirthdayLinkmanIdList();
        log.info("已设置生日的id:{}", linkmanIdList);
        List<Linkman> notSetList = linkmanService.list(new LambdaQueryWrapper<Linkman>()
                .eq(Linkman::getCustomerId, customerId)
                .eq(Linkman::getValidFlag, VALID_TRUE)
                .isNotNull(Linkman::getLinkmanBirthday)
                .notIn(linkmanIdList.size() > 0, Linkman::getLinkmanId, linkmanIdList)
                .select(Linkman::getLinkmanId, Linkman::getLinkmanName));

        // 转换结果到简化对象
        List<NoSetBirthdayVo.LinkmanSimple> simpleList = notSetList.stream()
                .map(l -> NoSetBirthdayVo.LinkmanSimple.builder()
                        .linkmanId(l.getLinkmanId())
                        .linkmanName(l.getLinkmanName())
                        .build())
                .collect(Collectors.toList());

        NoSetBirthdayVo noSetBirthdayVo = new NoSetBirthdayVo(notSetList.size(), simpleList);
        return ResultData.successData(noSetBirthdayVo);
    }

    /**
     * 查询当月节日数量
     */
    @Override
    public ResultData getHolidayCount() {
        Customer customer = SaTokenUtilPy.getCustomer();
        Long customerId = customer.getCustomerId();

        //获取这个月过生日的人数
        int[] birthNumArray = {0};
        int[] holidayNumArray = {0};
        int[] customNumArray = {0};
        HolidayDataModel model = new HolidayDataModel();

        List<Linkman> linkmanList = linkmanService.list(new LambdaQueryWrapper<Linkman>()
                .isNotNull(Linkman::getLinkmanBirthday)
                .eq(Linkman::getCustomerId, customerId)
                .eq(Linkman::getValidFlag, VALID_TRUE)
        );
        log.info("获取这个月过生日的人数:{}", linkmanList.size());

        //获取这个月月初
        LocalDate startDate = LocalDate.of(LocalDate.now().getYear(), LocalDate.now().getMonth(), 1);
        //获取这个月月底
        LocalDate endDate = LocalDate.of(LocalDate.now().getYear(), LocalDate.now().getMonth(), LocalDate.now().lengthOfMonth());
        if (linkmanList != null && linkmanList.size() != 0) {
            linkmanList.forEach(linkman -> {
                Holiday holiday1 = new Holiday();
                holiday1.setStartTime(linkman.getLinkmanBirthday());
                holiday1.setHolidayType(linkman.getBirthdayType());
                holiday1.setPeriod(1);
                holiday1.setPeriodCount(1);
                holiday1.setHolidaySort(0);
                LocalDate date = TimeUtils.getNextExecuteDate(0,holiday1, startDate);
                if ((date.isEqual(startDate) || date.isAfter(startDate))
                        && (date.isEqual(endDate) || date.isBefore(endDate))) {
                    log.info("查询当月节日数量linkman2:{}", date);
                    birthNumArray[0] += 1;
                }
            });
        }
        model.setBirthNum(birthNumArray[0]);
        List<Holiday> holidayList = list(new LambdaQueryWrapper<Holiday>()
                .eq(Holiday::getCustomerId, NUMBER_0)
                .ne(Holiday::getHolidayId, 6)
                .eq(Holiday::getValidFlag, VALID_TRUE)
        );

        if (holidayList != null && holidayList.size() != 0) {
            holidayList.forEach(holiday -> {
                LocalDate date = TimeUtils.getNextExecuteDate(0,holiday, startDate);
                if ((date.isEqual(startDate) || date.isAfter(startDate))
                        && (date.isEqual(endDate) || date.isBefore(endDate))) {
                    holidayNumArray[0] += 1;
                }
            });
        }
        List<Holiday> customHolidayList = list(new LambdaQueryWrapper<Holiday>()
                .eq(Holiday::getCustomerId, customerId)
                .eq(Holiday::getValidFlag, VALID_TRUE)
        );
        if (customHolidayList != null && customHolidayList.size() != 0) {
            customHolidayList.forEach(holiday -> {
                LocalDate date = TimeUtils.getNextExecuteDate(0,holiday, startDate);
                if ((date.isEqual(startDate) || date.isAfter(startDate))
                        && (date.isEqual(endDate) || date.isBefore(endDate))) {
                    log.info("自定义节日:{}", date);
                    customNumArray[0] += 1;
                }
            });
        }
        model.setHolidayNum(holidayNumArray[0]);
        model.setCustomNum(customNumArray[0]);
        return ResultData.successData(model);
    }
    /**
     * 查询节日详情
     */
    @Override
    public ResultData getDetail(Long holidayId) {
        Holiday holiday = getById(holidayId);
        return ResultData.successData(holiday);
    }
}
